package com.mfp.java.testYou.db.mySql;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.jasypt.util.password.BasicPasswordEncryptor;

import com.mfp.java.testYou.db.model.Answer;
import com.mfp.java.testYou.db.model.CompletedTest;
import com.mfp.java.testYou.db.model.Question;
import com.mfp.java.testYou.db.model.Test;
import com.mfp.java.testYou.db.model.User;
import com.mfp.java.testYou.db.model.UserRole;

public class ObjectsUtil {
	
	
	public static User createUser(ResultSet rs) throws SQLException {
		User user = new User();
		
		user.setId(rs.getInt(1));
		user.setUserName(rs.getString(2));
		user.setLang(rs.getString(4));
		if (rs.getString(5).equals(UserRole.ADMIN.toString())) {
			user.setRole(UserRole.ADMIN);
		}
		if (rs.getString(5).equals(UserRole.USER.toString())) {
			user.setRole(UserRole.USER);
		}
		return user;
	}
	
	public static Test createTest(ResultSet rs) throws SQLException {
		Test test = new Test();
		
		test.setId(rs.getInt(1));
		test.setTitle(rs.getString(2));
		test.setFinalTest(rs.getBoolean(3));
		test.setAllowHints(rs.getBoolean(4));
		
		return test;
	}

	public static Question createQuestion(ResultSet rs) throws SQLException {
		Question question = new Question();
		
		question.setId(rs.getInt(1));
		question.setText(rs.getString(2));
		question.setHint(rs.getString(3));
		
		return question;
	}

	public static Answer createAnswer(ResultSet rs) throws SQLException {
		Answer answer = new Answer();
		
		answer.setId(rs.getInt(1));
		answer.setText(rs.getString(2));
		answer.setCorect(rs.getBoolean(3));
		answer.setQuestionId(rs.getInt(4));
		
		return answer;
	}

	public static String encryptPass(CharSequence pass) {
		BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
		return passwordEncryptor.encryptPassword(pass.toString());
	}
	
	public static boolean passwordIsCorrect(String pass, String DBPass) {
		BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
		if (passwordEncryptor.checkPassword(pass, DBPass)) {
		  return true;
		}
		return false;
	}

	public static CompletedTest createCompletedTest(ResultSet rs) throws SQLException {
		CompletedTest ctest = new CompletedTest();
		
		ctest.setId(rs.getInt(1));
		ctest.setUserName(rs.getString(2));
		ctest.setTitle(rs.getString(3));
		ctest.setResult(rs.getFloat(4));
		ctest.setDate(rs.getDate(5));
		
		return ctest;
	}

}
